package com.pig.easy.bpm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pig.easy.bpm.constant.BpmConstant;
import com.pig.easy.bpm.dto.request.FormReqDTO;
import com.pig.easy.bpm.dto.response.DictItemDTO;
import com.pig.easy.bpm.dto.response.DynamicFormDataDTO;
import com.pig.easy.bpm.dto.response.FormDTO;
import com.pig.easy.bpm.dto.response.TreeItemDTO;
import com.pig.easy.bpm.entity.FormDO;
import com.pig.easy.bpm.entityError.EntityError;
import com.pig.easy.bpm.mapper.FormMapper;
import com.pig.easy.bpm.service.DictItemService;
import com.pig.easy.bpm.service.FormService;
import com.pig.easy.bpm.utils.BeanUtils;
import com.pig.easy.bpm.utils.CommonUtils;
import com.pig.easy.bpm.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author pig
 * @since 2020-05-28
 */
@org.apache.dubbo.config.annotation.Service(timeout = 30*1000)
@Slf4j
public class FormServiceImpl extends BeseServiceImpl<FormMapper, FormDO> implements FormService {

    @Autowired
    FormMapper formMapper;
    @Autowired
    DictItemService dictItemService;

    @Override
    public Result<PageInfo> getListByCondition(FormReqDTO formReqDTO) {

        if (formReqDTO == null) {
            return Result.responseError(EntityError.ILLEGAL_ARGUMENT_ERROR);
        }
        int pageIndex = CommonUtils.evalInt(formReqDTO.getPageIndex(), DEFAULT_PAGE_INDEX);
        int pageSize = CommonUtils.evalInt(formReqDTO.getPageSize(), DEFAULT_PAGE_SIZE);

        PageHelper.startPage(pageIndex, pageSize);
        FormDO form = BeanUtils.switchToDO(formReqDTO, FormDO.class);
        List<FormDTO> formList = formMapper.getListByCondition(form);
        if (formList == null) {
            formList = new ArrayList<>();
        }
        PageInfo<FormDTO> pageInfo = new PageInfo<>(formList);
        return Result.responseSuccess(pageInfo);
    }

    @Override
    public Result<FormDTO> getFormByFormKey(String formKey) {

        if (StringUtils.isEmpty(formKey)) {
            return Result.responseError(EntityError.ILLEGAL_ARGUMENT_ERROR);
        }

        FormDO formDO = formMapper.selectOne(new QueryWrapper<>(FormDO.builder().formKey(formKey).build()));
        if(formDO == null){
            return Result.responseError(EntityError.DATA_NOT_FOUND_ERROR);
        }
        FormDTO formDTO = BeanUtils.switchToDTO(formDO,FormDTO.class);
        return Result.responseSuccess(formDTO);
    }

    @Override
    public Result<Integer> insertForm(FormReqDTO formReqDTO) {

        if (formReqDTO == null
                || StringUtils.isEmpty(formReqDTO.getTenantId())
                || StringUtils.isEmpty(formReqDTO.getFormKey())) {
            return Result.responseError(EntityError.ILLEGAL_ARGUMENT_ERROR);
        }
        // 默认 key 格式   租户 +":" + key
        if (!formReqDTO.getFormKey().startsWith((formReqDTO.getTenantId()))) {
            formReqDTO.setFormKey(formReqDTO.getTenantId()
                    + BpmConstant.COMMON_CODE_SEPARATION_CHARACTER
                    + "form"
                    + BpmConstant.COMMON_CODE_SEPARATION_CHARACTER
                    + formReqDTO.getFormKey());
        }
        FormDO form = BeanUtils.switchToDO(formReqDTO, FormDO.class);
        Integer num = formMapper.insert(form);
        return Result.responseSuccess(num);
    }

    @Override
    public Result<Integer> updateFormByFormKey(FormReqDTO formReqDTO) {

        if (formReqDTO == null
                || StringUtils.isEmpty(formReqDTO.getFormKey())) {
            return Result.responseError(EntityError.ILLEGAL_ARGUMENT_ERROR);
        }

        FormDO form = BeanUtils.switchToDO(formReqDTO, FormDO.class);
        Integer num = formMapper.updateForm(form);
        return Result.responseSuccess(num);
    }

    @Override
    public Result<DynamicFormDataDTO> getInitForm(String formKey) {

        DynamicFormDataDTO dynamicFormDataDTO = new DynamicFormDataDTO();
        Map<String, List<TreeItemDTO>> dynamicDataMap = new HashMap<>();

        if (StringUtils.isEmpty(formKey)) {
            dynamicFormDataDTO.setDynamicDataMap(dynamicDataMap);
            return Result.responseSuccess(dynamicFormDataDTO);
        }

        Result<FormDTO> result2 = getFormByFormKey(formKey);
        if (result2.getEntityError().getCode() != EntityError.SUCCESS.getCode()) {
            return Result.responseError(result2.getEntityError());
        }

        dynamicFormDataDTO.setFormJsonData(StringEscapeUtils.unescapeJava(result2.getData().getFormData()));
        List<TreeItemDTO> dynamicKeyList = null;
        Result<List<DictItemDTO>> result3 = null;
        TreeItemDTO treeItemDTO = null;
        JSONObject jsonObject = JSON.parseObject(result2.getData().getFormData());
        if (jsonObject.containsKey(BpmConstant.DYNAMIC_KEY_LIST)) {
            JSONArray jsonArray = jsonObject.getJSONArray(BpmConstant.DYNAMIC_KEY_LIST);
            for (Object obj : jsonArray) {

                if (obj != null && !StringUtils.isEmpty(obj.toString())) {
                    dynamicKeyList = new ArrayList<>();
                    result3 = dictItemService.getListByDictCode(obj.toString());
                    if (result3.getEntityError().getCode() != EntityError.SUCCESS.getCode()) {
                        log.error("getInitForm getListByDictCode error , message is {}", result3.getEntityError());
                        continue;
                    }

                    for (DictItemDTO dictItem : result3.getData()) {
                        treeItemDTO = new TreeItemDTO();
                        treeItemDTO.setLabel(dictItem.getItemText());
                        try {
                            treeItemDTO.setValue(Integer.valueOf(dictItem.getItemValue()));
                        } catch (Exception e) {
                            treeItemDTO.setValue(dictItem.getItemValue());
                        }
                        dynamicKeyList.add(treeItemDTO);
                    }

                    dynamicDataMap.put(obj.toString(), dynamicKeyList);
                }
                dynamicFormDataDTO.setDynamicDataMap(dynamicDataMap);
            }
        }
        return Result.responseSuccess(dynamicFormDataDTO);
    }
}
